package com.wangtao.stock.common;

import com.alibaba.fastjson.JSON;
import com.wangtao.stock.enums.ExceptionEnum;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.net.BindException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    public JsonResult bindException(Exception exception) {
        JsonResult jsonResult = null;
        if (exception instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
            List<ObjectError> allErrors = methodArgumentNotValidException.getBindingResult().getAllErrors();
            String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
            jsonResult = JsonResult.fail(ExceptionEnum.PARAMS_VALID_ERROR.getCode(), message);
        }
        if (exception instanceof ConstraintViolationException) {
            Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) exception)
                    .getConstraintViolations();
            List<String> errors = new ArrayList<>();
            for (ConstraintViolation<?> violation : constraintViolations) {
                errors.add(violation.getMessage());
            }
            jsonResult = JsonResult.fail(ExceptionEnum.PARAMS_VALID_ERROR.getCode(), JSON.toJSONString(errors));
        }
        return jsonResult;
    }
}
